package com.hrp.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2018/8/1 0001.
 */

@Configuration
@MapperScan(basePackages = {JiraDataSourceConfig.PACKAGE}, sqlSessionFactoryRef = "jiraSqlSessionFactory")
public class JiraDataSourceConfig {


    static final String PACKAGE = "com.hrp.*.jiradao";
    //static final String MAPPACKAGE = "com.hrp.*.jiramapper";
    //static final String MAPPER_LOCATION = "classpath:com.hrp.*.jiramapper/*.xml";

    @Value("${jira.datasource.url}")
    private String url;

    @Value("${jira.datasource.username}")
    private String user;

    @Value("${jira.datasource.password}")
    private String password;

    @Value("${jira.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "jiraDataSource")
    public DataSource jiraDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "jiraTransactionManager")
    public DataSourceTransactionManager jiraTransactionManager() {
        return new DataSourceTransactionManager(jiraDataSource());
    }

    @Bean(name = "jiraSqlSessionFactory")
    public SqlSessionFactory jiraSqlSessionFactory(@Qualifier("jiraDataSource") DataSource jiraDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(jiraDataSource);
        //sessionFactory.setMapperLocations(
                //new PathMatchingResourcePatternResolver().getResources(JiraDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
